<template>
  <div class="page-container">
    <!-- 主页面 -->
    <div
      v-if="!showDetailView"
      class="main-view animate__animated"
      :class="{
        'animate__fadeOut': isTransitioning && !isReturning,
        'animate__fadeIn': isReturning
      }"
    >
      <div class="p-6 space-y-4">
        <!-- 搜索条件 -->
        <el-card shadow="never" class="rounded-lg mb-4">
          <div class="flex items-center gap-2 mb-4 text-14px">
            <div class="font-bold text-#606266 mr-2">甲醇制氢装置</div>
            <div class="w-[91px] h-[35px] bg-[#7FFF88] rounded text-#222222 flex items-center justify-center">无报警</div>
            <div class="w-[91px] h-[35px] bg-[#FFD37F] rounded text-#222222 flex items-center justify-center">H/L</div>
            <div class="w-[91px] h-[35px] bg-[#FF7F7F] rounded text-#222222 flex items-center justify-center">HH/LL</div>
            <div class="w-[91px] h-[35px] bg-[#DC99FF] rounded text-#222222 flex items-center justify-center">连锁</div>
          </div>
          <el-form :model="filters" label-position="top" class="search-form" @keyup.enter.native="handleQuery">
            <el-row :gutter="12" align="bottom">
              <el-col :xs="24" :sm="12" :lg="5">
                <el-form-item label="设备位号">
                  <el-input v-model="filters.deviceCode" placeholder="请输入" clearable @keyup.enter.native="handleQuery"/>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="5">
                <el-form-item label="系统位置">
                  <el-input v-model="filters.systemLocation" placeholder="请输入" clearable @keyup.enter.native="handleQuery"/>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="5">
                <el-form-item label="设备合格">
                  <el-select v-model="filters.deviceStatus" clearable placeholder="请选择">
                    <el-option label="无效" value="无效"/>
                    <el-option label="低" value="低"/>
                    <el-option label="中" value="中"/>
                    <el-option label="高" value="高"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :sm="12" :lg="5">
                <el-form-item label="报警状态">
                  <el-select v-model="filters.alarmStatus" clearable placeholder="请选择">
                    <el-option label="无报警" value="无报警"/>
                    <el-option label="H/L" value="H/L"/>
                    <el-option label="HH/LL" value="HH/LL"/>
                    <el-option label="连锁" value="连锁"/>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="24" :lg="4" class="flex justify-end items-end">
                <el-button type="primary" :loading="queryLoading" @click="handleQuery">
                  <el-icon class="mr-1">
                    <Search/>
                  </el-icon>
                  查询
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-card>

        <!-- 设备状态网格显示 -->
        <el-card shadow="never" class="rounded-lg">
          <div v-loading="dataLoading">
            <div v-for="section in deviceSections" :key="section.id" class="mb-6">
              <div class="flex items-center gap-2 mb-3">
                <span class="card-title font-bold text-#606266">{{ section.title }}</span>
              </div>
              <div class="grid grid-cols-15 gap-2">
                <div
                  v-for="(item, index) in section.devices"
                  :key="`${section.id}-${index}`"
                  :class="getTagClass(item.status)"
                  class="px-3 py-2 rounded text-center text-sm font-medium !text-#222222 cursor-pointer hover:opacity-80 transition-opacity"
                  @click="onDeviceClick(item, section)"
                >
                  {{ item.code }}
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 详情分析页面 -->
    <div
      v-if="showDetailView"
      class="detail-view animate__animated"
      :class="{
        'animate__fadeIn': !isReturning,
        'animate__fadeOut': isReturning
      }"
    >
      <div class="p-6">
        <DeviceDetailAnalysis
          :selected-device="selectedDevice"
          :selected-section="selectedSection"
          :device-sections="deviceSections"
          @back="handleBack"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref} from 'vue';
import {ElMessage} from 'element-plus';
import {Search} from '@element-plus/icons-vue';
import DeviceDetailAnalysis from './components/DeviceDetailAnalysis.vue';

interface DeviceItem {
  id: number;
  code: string;
  systemLocation: string;
  status: string;
  alarmTime?: string;
  description?: string;
}

interface DeviceSection {
  id: string;
  title: string;
  devices: DeviceItem[];
}

const filters = reactive({
  deviceCode: '',
  systemLocation: '',
  deviceStatus: '',
  alarmStatus: ''
});

const queryLoading = ref(false);
const dataLoading = ref(false);

// 详情页面状态
const showDetailView = ref(false);
const selectedDevice = ref<DeviceItem | null>(null);
const selectedSection = ref<DeviceSection | null>(null);

// 动画状态
const isTransitioning = ref(false);
const isReturning = ref(false);

// 生成FIC1207标签数据
const generateFICData = (count: number) => {
  const statuses = ['normal', 'warning', 'danger', 'normal'];
  const data: DeviceItem[] = [];

  for (let i = 0; i < count; i++) {
    const status = statuses[i % statuses.length];
    data.push({
      id: i + 1,
      code: 'FIC1207',
      systemLocation: '甲醇储罐监测',
      status,
    });
  }
  return data;
};

// 设备区域数据配置
const deviceSections = ref<DeviceSection[]>([
  {
    id: 'butene-distillation',
    title: '丁烯精馏塔',
    devices: generateFICData(30)
  },
  {
    id: 'ethylene-oxide',
    title: '环氧乙烷精馏塔',
    devices: generateFICData(30)
  },
  {
    id: 'butene-tank',
    title: '丁烯储罐区',
    devices: generateFICData(30)
  }
]);

// 获取标签样式类
const getTagClass = (status: string) => {
  switch (status) {
    case 'normal':
      return 'bg-#7FFF88';
    case 'warning':
      return 'bg-#FFD37F';
    case 'danger':
      return 'bg-#FF7F7F';
    default:
      return 'bg-#7FFF88';
  }
};

const handleQuery = () => {
  dataLoading.value = true;
  setTimeout(() => {
    dataLoading.value = false;
    ElMessage.success('查询完成');
  }, 500);
};

// 设备点击事件
const onDeviceClick = (device: DeviceItem, section: DeviceSection) => {
  // 只有报警状态（danger）的设备才能点击进入详情
  if (device.status === 'danger') {
    selectedDevice.value = device;
    selectedSection.value = section;
    isTransitioning.value = true;

    // 延迟显示详情页面，让主页面先执行退出动画
    setTimeout(() => {
      showDetailView.value = true;
      isTransitioning.value = false;
    }, 100);
  }
};

// 返回主页面
const handleBack = () => {
  isReturning.value = true;

  // 延迟隐藏详情页面，让退出动画执行完成
  setTimeout(() => {
    showDetailView.value = false;
    selectedDevice.value = null;
    selectedSection.value = null;

    // 再次延迟重置状态，让主页面进入动画执行
    setTimeout(() => {
      isReturning.value = false;
    }, 100);
  }, 500); // 500ms 对应动画时长
};
</script>

<style lang="scss" scoped>
.card-title {
  position: relative;
  padding-left: 18px;
  font-size: 14px;
}

.card-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 4px;
  width: 18px;
  height: 13px;
  background: url('@/assets/images/card-title-prefix.png') no-repeat center / contain;
}

// 页面容器
.page-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

// 主页面和详情页面的基础样式
.main-view,
.detail-view {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #f5f5f5;
}

// animate.css 动画时长调整
.animate__animated {
  animation-duration: 0.5s;
}
</style>
